from multiprocessing import Process
from socket import *
from dict_db import  *
class Handle(Process):
    def __init__(self,conn):
        self.conn=conn
        self.db=Dict()
        self.name=''
        super().__init__()

   #Loop accept request
    def run(self):
        while True:
            request=self.conn.recv(1024)
            tmp=request.decode().split('\t')
            if tmp[0]=="R":
                self.register(tmp[1],tmp[2])
            if tmp[0]=="L":
                self.login(tmp[1],tmp[2])
            if tmp[0]=="r":
                self.query_word(tmp[1])
            if tmp[0]=="H":
                self.viewhistory(self.name)

        self.db.close()
        self.conn.close()

    def register(self,name,password):
        if self.db.register(name,password):
            self.conn.send(b'T')
        else:
            self.conn.send(b'F')
    def login(self,name,password):
        if self.db.login(name,password):
            self.conn.send(b'T')
            self.name=name
        else:
            self.conn.send(b'F')

    def query_word(self,word):
        mean= self.db.query_word(word)
        if mean:
            self.conn.send(mean[0].encode())
            self.insert_hist(self.name,word)
        else:
            self.conn.send(b'not found')

    def insert_hist(self, name,word):
        self.db.insert_hist(name,word)
        pass
    def viewhistory(self,username):
       wordlist= self.db.viewhistory(username)
       response="\n".join(wordlist) if wordlist else "no more history"
       self.conn.send(response.encode())



class Dictserver:

    def __init__(self,host='0.0.0.0',port=8888):
        self.host=host
        self.port=port
        self.address=(self.host,self.port)
        self.sock=self._create_sock()

    def _create_sock(self):
        sock=socket()
        sock.bind(self.address)
        return sock
        pass

    def serve_forever(self):
        self.sock.listen(5)
        print(f'listen the {self.port}')
        while True:
            conn,addr=self.sock.accept()
            print(f'connect from {addr}')
            #create a process for user
            handle=Handle(conn)
            handle.start()

if __name__ == '__main__':
    dict=Dictserver()
    dict.serve_forever()